package com.soloyogame.anitoys.item.web.controller.front.orders;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.soloyogame.anitoys.db.bean.OrderCustInputInfo;
import com.soloyogame.anitoys.db.bean.Spec;
import com.soloyogame.anitoys.db.commond.Account;
import com.soloyogame.anitoys.db.commond.AccountCoupon;
import com.soloyogame.anitoys.db.commond.AccountDeductibleVoucher;
import com.soloyogame.anitoys.db.commond.AccountFinance;
import com.soloyogame.anitoys.db.commond.Address;
import com.soloyogame.anitoys.db.commond.Business;
import com.soloyogame.anitoys.db.commond.BusinessShipping;
import com.soloyogame.anitoys.db.commond.BusinessShippingDetail;
import com.soloyogame.anitoys.db.commond.CartInfo;
import com.soloyogame.anitoys.db.commond.Express;
import com.soloyogame.anitoys.db.commond.Help;
import com.soloyogame.anitoys.db.commond.Order;
import com.soloyogame.anitoys.db.commond.Orderdetail;
import com.soloyogame.anitoys.db.commond.Orderlog;
import com.soloyogame.anitoys.db.commond.Orderpay;
import com.soloyogame.anitoys.db.commond.Ordership;
import com.soloyogame.anitoys.db.commond.PayInfo;
import com.soloyogame.anitoys.db.commond.Product;
import com.soloyogame.anitoys.db.commond.SystemSetting;
import com.soloyogame.anitoys.item.web.controller.front.FrontBaseController;
import com.soloyogame.anitoys.item.web.controller.front.util.LoginUserHolder;
import com.soloyogame.anitoys.item.web.controller.front.util.RequestHolder;
import com.soloyogame.anitoys.service.AccountCouponService;
import com.soloyogame.anitoys.service.AccountDeductibleVoucherService;
import com.soloyogame.anitoys.service.AccountFinanceService;
import com.soloyogame.anitoys.service.AddressService;
import com.soloyogame.anitoys.service.BusinessService;
import com.soloyogame.anitoys.service.ExpressService;
import com.soloyogame.anitoys.service.HelpService;
import com.soloyogame.anitoys.service.OrderBusinessShippingService;
import com.soloyogame.anitoys.service.OrderService;
import com.soloyogame.anitoys.service.OrderdetailService;
import com.soloyogame.anitoys.service.OrderpayService;
import com.soloyogame.anitoys.service.ProductService;
import com.soloyogame.anitoys.service.SpecService;
import com.soloyogame.anitoys.service.SystemSettingService;
import com.soloyogame.anitoys.util.JsonUtil;
import com.soloyogame.anitoys.util.KeyTool;
import com.soloyogame.anitoys.util.cache.RedisCacheProvider;
import com.soloyogame.anitoys.util.constants.ManageContainer;




/**
 * 门户订单服务类
 *
 * @author shaojian
 */
@Controller("frontOrderAction")
@RequestMapping("order")
public class OrderAction extends FrontBaseController<Order> {
    private static final Logger logger = LoggerFactory.getLogger(OrderAction.class);
    private static final long serialVersionUID = 1L;
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderdetailService orderdetailService;
    @Autowired
    private OrderpayService orderpayService;
    @Autowired
    private ProductService productService;

    @Autowired
    private AddressService addressService;
    @Autowired
    private RedisCacheProvider redisCacheProvider;
    @Autowired
    private OrderBusinessShippingService orderBusinessShippingService;
    @Autowired
    private AccountFinanceService accountFinanceService;
    @Autowired
    private AccountCouponService accountCouponService;
    @Autowired
    private SpecService specService;
    @Autowired
    private BusinessService businessService;
    @Autowired
    private AccountDeductibleVoucherService accountDeductibleVoucherService;
    @Autowired
    private HelpService helpService;
    @Autowired
	private ExpressService expressService;
    private String url;                                    //页面的上一个跳转的url
	@Autowired
    private SystemSetting systemSetting;
    @Autowired
    private SystemSettingService systemSettingService;
    
    public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

    @Override
    public OrderService getService() {
        return orderService;
    }

    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }

    /**
     * 订单确认页面，点击这个页面的确认支付按钮则会跳转到支付宝等的支付页面
     *
     * @return
     */
    @RequestMapping("orderConfirm")
    public String orderConfirm() {
        logger.info("into method orderConfirm");
        return "order/confirmOrder";
    }


    /**
     * check 商品详情页面进入订单确认页面
     *
     * @param model
     * @param request
     * @return
     * @author j.ren
     */
    @RequestMapping(value = "checkPlacPayFrom")
    @ResponseBody
    public Object checkPlacPayFrom(HttpServletRequest request, ModelMap model, HttpServletResponse response)
    {
        Map<String, Object> result = new HashMap<String, Object>();
        url = RequestHolder.getRequest().getHeader("Referer");                  //获得前一页的URL
		RequestHolder.getRequest().getSession().setAttribute("url", url);
        //获得登陆用户信息，若获取空，则跳转登陆页面
        Account account = getLoginAccount();
        if (account == null || StringUtils.isBlank(account.getAccount())) 
        {
            result.put("result", "notLogin");
            return result;
        }
        //获取前台传递商品id
        String productId = request.getParameter("productId");            //商品ID
        logger.info("productID = " + productId);
        //获取前台传递购买数量
        int qty = Integer.valueOf(request.getParameter("buyCount"));//购买数量
        //获取前台传递选中的规格id
        String specId = request.getParameter("buySpecID");            //选中的规格ID

        Map<String, String> check = checkPlacFromDetail(productId, qty, specId);

        result.put("result", check.get("result"));
        return result;


    }

    /**
     * 立即购买校验库存和限购
     *
     * @param productId
     * @param qty
     * @param specId
     * @return
     */
    private Map<String, String> checkPlacFromDetail(String productId, int qty, String specId)
    {
        Map<String, String> result = new HashMap<String, String>();
        //获得登陆用户信息，若获取空，则跳转登陆页面
        Account account = getLoginAccount();
        // 当前用户购买数量
        Integer account_product_xgslValue = 0;
        String account_product_xgsl = account.getId() + ManageContainer.account_product_xgsl + productId;
        if (redisCacheProvider.get(account_product_xgsl) != null) {
            account_product_xgslValue = Integer.valueOf(redisCacheProvider.get(account_product_xgsl).toString());
        }
        // 限购数量
        Integer product_spxgValue = 0;
        String product_spxg = productId + ManageContainer.product_xgsl;
        if (redisCacheProvider.get(product_spxg) != null) {
            product_spxgValue = Integer.valueOf(redisCacheProvider.get(product_spxg).toString());
        }

        //查询限购 约定限购数量为0时不限购
        if (product_spxgValue != 0) {
            if (qty + account_product_xgslValue > product_spxgValue) {
                result.put("result", "很抱歉，您已超过商品的最大购买数量！");
                return result;
            }
        }

        // 下单库存
        Integer product_xdkcValue = 0;
        if (StringUtils.isNotEmpty(specId)) {
            String product_xdkc = productId + ManageContainer.product_xdkc + specId;
            if(redisCacheProvider.get(product_xdkc)==null){
            	 Spec spec = specService.selectById(specId);
            	redisCacheProvider.put(product_xdkc, spec.getSpecStock());
            }
            product_xdkcValue = Integer.valueOf(redisCacheProvider.get(product_xdkc).toString());
        }


        /**
         * 检查内存库存是否已超卖，如果超库存不足，则提醒用户
         */
        if (qty > product_xdkcValue) {
            result.put("result", "很抱歉，商品库存不足！");
            return result;
        }

        result.put("result", "ok");
        return result;
    }

    /**
     * 从商品详情页面进入订单确认页面
     *
     * @param model
     * @param request
     * @return
     * @author zhangjing
     */
    @RequestMapping(value = "toPlacPayFromDetail", method = RequestMethod.POST)
    public String toPlacPayFromDetail(ModelMap model, HttpServletRequest request) {
        Account account = getLoginAccount();
        if (account == null || StringUtils.isBlank(account.getAccount())) {
            return page_toLoginRedirect;
        }
        //获取前台传递商品id
        String productID = request.getParameter("productId");            //商品ID
        logger.info("productID = " + productID);
        //获取前台传递购买数量
        int buyCount = Integer.valueOf(request.getParameter("buyCount"));//购买数量
        //获取前台传递选中的规格id
        String buySpecID = request.getParameter("buySpecID");            //选中的规格ID

        // 校验库存及立即购买
//         Map<String,String> checkResult = checkPlacFromDetail(productID,buyCount,buySpecID);

		/*if( !"ok".equals(checkResult.get("result"))) {
            model.addAttribute("errorMsg", checkResult.get("result"));
			return "cart/product/"+productID;
		} else {*/
        //若获取商品id为空或购买数量小于0，则抛出异常（“商品id传递失败！”）
        if (StringUtils.isEmpty(productID) || buyCount < 0) {
            throw new IllegalArgumentException("商品id传递失败！");
        }
        //根据商品id查询获取产品信息
        Product product = productService.selectById(productID);
        logger.info("现货/预售商品标识（1-现货，2-预售）：" + product.getProductType());
        //将客户购买数量赋值
        product.setBuyCount(buyCount);
            /*
             * 加载指定商品的规格信息
			 */
        if (StringUtils.isNotBlank(buySpecID)) {
            //根据选中的规格id查询获取规格信息
            Spec spec = specService.selectById(buySpecID);
            if (spec == null) {
                throw new NullPointerException("根据指定的规格" + buySpecID + "查询不到任何数据!");
            }
            //将匹配的规格信息赋值
            product.setBuySpecInfo(spec);
            //减少以后的逻辑判断，规格的价格等同于商品的价格
            product.setNowPrice(spec.getSpecPrice());
        }
        //根据用户id获取用户配送地址列表
        Address address = new Address();
        address.setAccountId(account.getId());
        List<Address> addressList = addressService.selectList(address);
        logger.info("用户" + account.getAccount() + "共有" + addressList.size() + "个地址");
        //将用户配送地址list传递前台
        model.addAttribute("addressList", addressList);
        model.addAttribute("addressListSize", addressList.size());
        List<Order> sonOrderList = new ArrayList<Order>();    //子订单集合
        Order sonOrder = new Order();    //子订单实体
        //子订单商品总金额 = 商品购买数量 * 商品现价
        sonOrder.setPtotal(Double.toString(product.getBuyCount() * Double.parseDouble(product.getNowPrice())));
        //若商品为现货商品 ，标记子订单类型为现货
        if (product.getProductType() == Order.PROD_TYPE_XIAN) {
            sonOrder.setOrderType(Order.PROD_TYPE_XIAN); //现货
            sonOrder.setRemark("现货商品订单");
            //子订单总金额，此处暂时将商品总金额赋值，后会根据优惠、抵扣、运费等金额更新
            sonOrder.setAmount(Double.toString(product.getBuyCount() *
                    Double.parseDouble(product.getNowPrice())));//子订单总金额 -- 定金（子订单商品购买数量 * 商品现价）
        }
        //若商品为预售商品，标记子订单类型为预售
        else if (product.getProductType() == Order.PROD_TYPE_YUSHOU) {
            sonOrder.setOrderType(Order.PROD_TYPE_YUSHOU); //预售
            String depositType = request.getParameter("depositType");//预售商品的支付方式(1:定金预定2：全款预定)
            model.addAttribute("depositType", depositType);
            sonOrder.setRemark("预售商品订单");
            //预售商品的定金预定
            if (Integer.valueOf(depositType) == 1) {
                //子订单总金额（此处暂时将商品总金额赋值，后会根据优惠、抵扣、运费等金额更新）
                sonOrder.setAmount(Double.toString(product.getBuyCount() *
                        Double.parseDouble(product.getNowPrice())));
                //子订单总金额 -- 定金（子订单商品购买数量 * 商品预售价）
                sonOrder.setAdvancePrice(Double.toString(product.getBuyCount() *
                        Double.parseDouble(product.getDepositPrice())));//首付款 -- 定金（子订单商品购买数量 * 商品预售价）
                sonOrder.setBalancePrice(Double.toString(Double.parseDouble(sonOrder.getAmount()) -
                        Double.parseDouble(sonOrder.getAdvancePrice())));//补款余额 -- 预售商品总价 - 首付款
            }
            //全款预定
            else {
                //子订单总金额（此处暂时将商品总金额赋值，后会根据优惠、抵扣、运费等金额更新）
                sonOrder.setAmount(Double.toString(product.getBuyCount() *
                        Double.parseDouble(product.getNowPrice())));
                //子订单总金额 -- 定金（子订单商品购买数量 * 商品预售价）
                sonOrder.setAdvancePrice(Double.toString(product.getBuyCount() *
                        Double.parseDouble(product.getNowPrice())));     //首付款 -- 定金（子订单商品购买数量 * 商品预售价）
                sonOrder.setBalancePrice(Double.toString(Double.parseDouble(sonOrder.getAmount()) -
                        Double.parseDouble(sonOrder.getAdvancePrice())));//补款余额 -- 预售商品总价 - 首付款
            }
        }
        //创建订单号
        String orderCode = KeyTool.creatKey();
        sonOrder.setOrderCode(orderCode);
        sonOrder.setOrderCodeView(orderCode.substring(8));
            /*
             * 根据客户购买商品创建订单详情信息
			 * 并赋值到子订单orderDetailList属性中
			 * 因此方法是从商品详细页面进入，故一个子订单对应的是一个子订单详情
			 */
        List<Orderdetail> orderDetailList = new ArrayList<Orderdetail>();
        Orderdetail orderdetail = createOrderDetail(product);
        orderDetailList.add(orderdetail);
        sonOrder.setOrderdetail(orderDetailList);

        sonOrder.setQuantity(product.getBuyCount());
        sonOrder.setAccount(account.getId());
        //子订单所获积分 = 商品积分 * 购买数量
        sonOrder.setScore(product.getScore() * product.getBuyCount());
        sonOrder.setBusinessId(product.getBusinessId());
        if (StringUtils.isNotBlank(product.getBusinessId())) {
            //根据商品商家编号查询获取商家信息
            Business business = businessService.selectById(product.getBusinessId());
            sonOrder.setBusinessName(business.getBusinessName());        //子订单商家名称
        }
        //根据商家id获取配送方式list
        List<BusinessShipping> businessShippingList =
                orderBusinessShippingService.queryOrderBusinessShipping(product.getBusinessId());
        sonOrder.setBusinessShippingList(businessShippingList);
            /*
             * 根据用户id和商家id获取用户有效优惠券list
			 * 创建一个优惠券实体，表示用户不使用优惠券，并添加到list第一位，用于前台默认展示
			 * 并将优惠券list赋值到子订单中
			 */
        List<AccountCoupon> accountCouponList =
                accountCouponService.selectAccountCouponList(account.getId(), product.getBusinessId());
            /*AccountCoupon accountCoupon = new AccountCoupon();
            accountCoupon.setId("MF0001");
			accountCoupon.setCouponName("未使用优惠券");
			accountCoupon.setCouponValue("0.0");
			accountCouponList.add(0, accountCoupon);*/
        sonOrder.setAccountCouponList(accountCouponList);
        //用于区分预售/现货商品子订单	0 -- 预售 1 -- 现货
        sonOrder.setOrderFlag(0);
        sonOrderList.add(sonOrder);
        //将子订单list传递前台
        model.addAttribute("sonOrderList", sonOrderList);
        //根据用户信息和子订单list创建父订单信息
        Order parentOrder = createParentOrder(account, sonOrderList);
            /*
             * 根据用户id获取用户平台抵扣券list
			 * 创建一个抵扣券实体，表示用户不使用抵扣券，并添加到list第一位，用于前台默认展示
			 * 并将抵扣券list赋值到父订单中
			 */
        List<AccountCoupon> accountVoucherList =
                accountCouponService.selectAccountVoucherList(account.getId());
            /*AccountCoupon accountVoucher = new AccountCoupon();
			accountVoucher.setId("MFPT0001");
			accountVoucher.setCouponName("未使用抵扣券");
			accountVoucher.setCouponValue("0.0");
			accountVoucherList.add(0, accountVoucher);*/
        parentOrder.setAccountVoucherList(accountVoucherList);
        //将父订单传递到前台
        model.addAttribute("parentOrder", parentOrder);
        //根据用户id获取用户积分信息
        int rank = 0;
        AccountFinance accountFinance =
                accountFinanceService.queryAccountFinanceByUserId(account.getId());
        if (accountFinance != null) {
            rank = accountFinance.getRank();
        }
        //将用户积分传递前台
        model.addAttribute("rank", rank);
        //将父订单存入redis中，做后面逻辑使用
        redisCacheProvider.put(account.getId() + "parentOrder", parentOrder);
        //应支付金额
        Double amount = 0.0;
        if (product.getProductType() == Order.PROD_TYPE_XIAN) {
            amount = Double.valueOf(parentOrder.getAmount());
        }
        //若商品为预售商品，标记子订单类型为预售
        else if (product.getProductType() == Order.PROD_TYPE_YUSHOU) {
            for (Order o : sonOrderList) {
                amount = amount + Double.valueOf(o.getAdvancePrice());
            }
        }
        model.addAttribute("amount", amount);
        //跳转到订单确认页面
        Help help = new Help();
        help.setStatus("y");
        List<Help> helpList = helpService.selectList(help);
        model.addAttribute("helpList", helpList);
        return "order/plac";
    }

    //}


    /**
     * 购物车进入订单确认页面，点击页面的去结算按钮进入订单确认页面
     *
     * @param model
     * @param ids   购物车中用户勾选的付款商品id
     * @return 跳转订单确认页面
     * @author zhangjing
     */
    @RequestMapping("plac")
    public String placPay(HttpServletRequest request, ModelMap model, String[] ids) {
        //获得用户信息
        Account account = getLoginAccount();
        //若获取登录用户信息为null，则跳到登陆页面
        if (account == null || StringUtils.isBlank(account.getAccount())) {
            return page_toLoginRedirect;
        }
        //根据登陆用户id获取用户地址列表
        Address address = new Address();
        address.setAccountId(account.getId());
        List<Address> addressList = addressService.selectList(address);
        logger.info("用户" + account.getAccount() + "共有" + addressList.size() + "个地址");
        //将用户地址list传递前台
        model.addAttribute("addressList", addressList);
        //获取用户选中的商品信列表（这里暂时生成一个临时的子订单，不进行插库）
        List<Order> sonOrderList = this.createSonOrderInfo(account, ids);
        logger.info("子订单个数：" + sonOrderList.size());
        //将临时子订单传递前台
        model.addAttribute("sonOrderList", sonOrderList);
        //根据子订单生成临时父订单
        Order parentOrder = this.createParentOrder(account, sonOrderList);
        //根据用户id获取用户平台抵扣券list
        List<AccountCoupon> accountVoucherList = accountCouponService.selectAccountVoucherList(account.getId());
        //生成一个默认的抵扣券，表示用户未使用任何抵扣券
		/*AccountCoupon accountCoupon = new AccountCoupon();
		accountCoupon.setId("MFPT0001");
		accountCoupon.setCouponName("未使用抵扣券");
		accountCoupon.setCouponValue("0.0");
		accountVoucherList.add(0, accountCoupon);*/
        parentOrder.setAccountVoucherList(accountVoucherList);
        //将父订单传递前台
        model.addAttribute("parentOrder", parentOrder);
        //将父订单信息存入radis缓存中，供后流程使用，注意绑定用户id
//		if(redisCacheProvider.get(account.getId() + "parentOrder") != null) {
//			redisCacheProvider.remove(account.getId() + "parentOrder");
//		}
        redisCacheProvider.put(account.getId() + "parentOrder", parentOrder);
        //根据用户id获取用户积分信息
        int rank = 0;
        AccountFinance accountFinance = accountFinanceService.queryAccountFinanceByUserId(account.getId());
        if (accountFinance != null) {
            rank = accountFinance.getRank();
        }
        //将用户积分信息传递前台
        model.addAttribute("rank", rank);
        //跳转到订单确认页面
        String depositType = request.getParameter("depositType");//预售商品的支付方式
        model.addAttribute("depositType", depositType);
        //应支付金额
        Double amount = 0.0;
        amount = Double.valueOf(parentOrder.getAmount());
        model.addAttribute("amount", amount);
        //帮助支持列表
        Help help = new Help();
        help.setStatus("y");
        List<Help> helpList = helpService.selectList(help);
        model.addAttribute("helpList", helpList);
        return "order/plac";
    }

    /**
     * 生成子订单集合
     *
     * @param account 登陆用户信息
     * @param ids     购物车中用户勾选的付款商品id
     * @return List<Order> 子订单集合
     * @author zhangjing
     */
    private List<Order> createSonOrderInfo(Account account, String[] ids) {
        List<Order> sonOrderList = new ArrayList<Order>();        //子订单集合，既返回结果集
        List<Product> productList = new ArrayList<Product>();        //用于存放购物车用户选中商品列表
        //从redis中获取用户购物车中所有商品列表
        CartInfo cartInfo = getMyCart();
        if (cartInfo == null || cartInfo.getProductList().size() == 0) {
            throw new NullPointerException("用户购物车中没有可支付的商品!");
        }
        //若用户有选中商品付款，则将勾选商品放入productList，供后使用
        if (ids != null && ids.length > 0) {
            for (int i = 0; i < ids.length; i++) {
                for (Iterator<Product> it = cartInfo.getProductList().iterator(); it.hasNext(); ) {
                    Product p = it.next();
                    if (p.getpSpecId().equals(ids[i])) {
                        productList.add(p);
                        break;
                    }
                }
            }
        }
        //创建用于存放用户选择付款现货商品集合
        List<Product> productXianList = new ArrayList<Product>();
        for (Product product : productList) {
            //logger.info("product.getBuySpecInfo().getId() = " + product.getBuySpecInfo().getId());
            logger.info("商品（" + product.getId() + "）标识（1-现货，2-预售）：" + product.getProductType() +
                    "\n" + "商家id = " + product.getBusinessId());
            //若商品为现货
            if (product.getProductType() == Order.PROD_TYPE_XIAN) {
                productXianList.add(product);
            }
            //若为预售商品
            else if (product.getProductType() == Order.PROD_TYPE_YUSHOU) {
                //随机生成子订单号
                String orderCode = KeyTool.creatKey();
                //创建子订单实体
                Order sonOrder = new Order();
                sonOrder.setOrderCode(orderCode);                        //子订单号
                sonOrder.setOrderCodeView(orderCode.substring(8));        //预防过长，只截取8位
                sonOrder.setNumber(product.getBuyCount());                //子订单商品购买数量
                sonOrder.setPtotal(Double.toString(product.getBuyCount() *
                        Double.parseDouble(product.getNowPrice())));    //子订单商品总价（子订单商品购买数量 * 商品现价）
                sonOrder.setQuantity(product.getBuyCount());            //子订单商品总数量
                
                sonOrder.setAmount(product.getTotal0());//子订单总金额 -- 定金（子订单商品购买数量 * 商品预售价）
                sonOrder.setAdvancePrice(Double.toString(product.getBuyCount() *
                        Double.parseDouble(product.getDepositPrice())));//首付款 -- 定金（子订单商品购买数量 * 商品预售价）
                sonOrder.setBalancePrice(Double.toString(Double.parseDouble(sonOrder.getPtotal()) -
                        Double.parseDouble(sonOrder.getAdvancePrice())));//补款余额 -- 预售商品总价 - 首付款
                sonOrder.setOrderType(Order.PROD_TYPE_YUSHOU);            //子订单类型
                sonOrder.setAccount(account.getId());                    //子订单用户id
                sonOrder.setScore(product.getScore());                    //子订单获赠的积分
                sonOrder.setBusinessId(product.getBusinessId());        //子订单商家编号
                sonOrder.setDepositType(product.getDepositType());    // 预售商品 订单支付方式
                if (!StringUtils.isBlank(product.getBusinessId())) {
                    //根据商品商家编号查询获取商家信息
                    Business business = businessService.selectById(product.getBusinessId());
                    sonOrder.setBusinessName(business.getBusinessName());//子订单商家名称
                }
                sonOrder.setIsSaleorder(0);                                //是否售后订单
                //根据商品商家编号获取商家配送方式list
                List<BusinessShipping> businessShippingList = orderBusinessShippingService.queryOrderBusinessShipping(product.getBusinessId());
                sonOrder.setBusinessShippingList(businessShippingList);    //子订单配送方式地址
                //根据用户id和商家编号获取该用户在该商家的优惠券list
                List<AccountCoupon> accountCouponList = accountCouponService.selectAccountCouponList(account.getId(), product.getBusinessId());
                //生成一个默认的优惠券，表示用户未使用任何优惠券
				/*AccountCoupon accountCoupon = new AccountCoupon();
				accountCoupon.setId("MF0001");
				accountCoupon.setCouponName("未使用优惠券");
				accountCoupon.setCouponValue("0.0");
				accountCouponList.add(0, accountCoupon);*/
                sonOrder.setAccountCouponList(accountCouponList);        //子订单商家优惠券
                sonOrder.setOrderFlag(0);                                //用于区分预售/现货商品子订单 0 -- 预售 1-- 现货
                sonOrder.setLowStocks("y");                                //子订单库存状态
                sonOrder.setRemark("预售商品订单");                            //子订单备注
                //子订单详情列表
                List<Orderdetail> orderDetailList = new ArrayList<Orderdetail>();
                Orderdetail orderdetail = this.createOrderDetail(product);
                orderDetailList.add(orderdetail);
                sonOrder.setOrderdetail(orderDetailList);
                sonOrder.setStatus(Order.order_status_init);            //子订单状态
                sonOrderList.add(sonOrder);
            }
        }
        //针对所有现货生成子订单 -- 同一个仓库的现售商品生成同一个子订单
        if (productXianList.size() >= 1) {
            while (true) {
                List<Product> productSamBusiness = new ArrayList<Product>();        //用于存放同一商家的商品
                //随机生成订单号
                String orderCode = KeyTool.creatKey();

                Product productXian = productXianList.get(productXianList.size() - 1);

                List<Orderdetail> orderDetailList = new ArrayList<Orderdetail>();
                Orderdetail orderdetail = this.createOrderDetail(productXian);
                orderDetailList.add(orderdetail);

                productSamBusiness.add(productXian);
                productXianList.remove(productXianList.size() - 1);
                int quantity = productXian.getBuyCount();        //商品个数
                double ptotal = productXian.getBuyCount() * Double.parseDouble(productXian.getNowPrice());
                int score = productXian.getScore();
                for (int i = productXianList.size() - 1; i >= 0; i--) {
                    if (productXian.getBusinessId().equals(productXianList.get(i).getBusinessId())) {
                        quantity += productXianList.get(i).getBuyCount();
                        ptotal += productXianList.get(i).getBuyCount() * Double.parseDouble(productXianList.get(i).getNowPrice());
                        score += productXianList.get(i).getScore();

                        Orderdetail orderdetailSam = this.createOrderDetail(productXianList.get(i));
                        orderdetailSam.setOrderID(orderCode);
                        orderDetailList.add(orderdetailSam);
                        productSamBusiness.add(productXianList.get(i));
                        productXianList.remove(i);
                    }
                }
                logger.info("商品个数：" + quantity + "，结算商品总金额：" + ptotal);
                Order sonOrder = new Order();    //子订单实体
                sonOrder.setOrderCode(orderCode);
                sonOrder.setOrderCodeView(orderCode.substring(8));
                sonOrder.setPtotal(Double.toString(ptotal));
                sonOrder.setQuantity(quantity);
                sonOrder.setAmount(sonOrder.getPtotal());
                sonOrder.setOrderType(Order.PROD_TYPE_XIAN); //现售
                sonOrder.setAccount(account.getId());
                sonOrder.setScore(score);
                sonOrder.setRemark("现售商品订单");
                sonOrder.setBusinessId(productXian.getBusinessId());
                if (!StringUtils.isBlank(productXian.getBusinessId())) {
                    Business business = businessService.selectById(productXian.getBusinessId());
                    sonOrder.setBusinessName(business.getBusinessName());
                }
                sonOrder.setBusinessShippingList(orderBusinessShippingService.queryOrderBusinessShipping(productXian.getBusinessId()));
                //优惠券
                List<AccountCoupon> accountCouponList = accountCouponService.selectAccountCouponList(account.getId(), productXian.getBusinessId());
                //logger.info("优惠券类型：" + accountCouponList.get(0).getCouponType());
				/*AccountCoupon accountCoupon = new AccountCoupon();
				accountCoupon.setId("MF0001");
				accountCoupon.setCouponName("未使用优惠券");
				accountCoupon.setCouponValue("0.0");
				accountCouponList.add(0, accountCoupon);*/
                sonOrder.setAccountCouponList(accountCouponList);
                sonOrder.setOrderFlag(1);
                sonOrder.setOrderdetail(orderDetailList);
                sonOrder.setStatus(Order.order_status_init);
                sonOrderList.add(sonOrder);
                //为了退出无限循环
                if (productXianList.size() == 0) {
                    break;
                }
            }
        }
        return sonOrderList;
    }

    /**
     * 创建父订单信息
     *
     * @param account      //登陆用户信息
     * @param sonOrderList //子订单列表
     * @return
     * @author zhangjing
     */
    private Order createParentOrder(Account account, List<Order> sonOrderList) {
        //创建大订单对象
        Order pareOrder = new Order();
        pareOrder.setOrders(sonOrderList);
        pareOrder.setAccount(account.getId());
        //随机生成订单号
        String orderCode = KeyTool.creatKey();
        pareOrder.setOrderCode(orderCode);
        pareOrder.setOrderCodeView(orderCode.substring(8));
        //计算商品总数量
        int quantity = 0;
        int score = 0;
        double ptotal = 0;        //子订单商品总金额
        double amount = 0;        //子订单总金额（区别预售）
        for (Order sonOrder : sonOrderList) {
            quantity += sonOrder.getQuantity();
            score += sonOrder.getScore();
            ptotal += Double.parseDouble(sonOrder.getPtotal());
            amount += Double.parseDouble(sonOrder.getAmount());
        }
        pareOrder.setQuantity(quantity);
        pareOrder.setScore(score);
        pareOrder.setPtotal(Double.toString(ptotal));         //订单商品总金额
        pareOrder.setStatus(Order.order_status_init);
        pareOrder.setPaystatus(Order.order_paystatus_n);
        //订单总金额 = 内存订单总金额 (初始默认大订单总金额 = 子订单商品总金额)
        pareOrder.setAmount(Double.toString(amount));
        if (sonOrderList.size() == 1) {
            pareOrder.setRemark("1笔订单");
        } else {
            pareOrder.setRemark("合并|" + sonOrderList.size() + "笔订单");
        }
        /*
		 * 对金额进行格式化，防止出现double型数字计算造成的益出。
		 */
        DecimalFormat df = new DecimalFormat("0.00");
        pareOrder.setAmount(df.format(Double.valueOf(pareOrder.getAmount())));//订单总金额
        pareOrder.setPtotal(df.format(Double.valueOf(pareOrder.getPtotal())));//订单商品总金额
        //pareOrder.setFee(df.format(Double.valueOf(pareOrder.getFee())));//订单总配送费
        return pareOrder;
    }

    /**
     * 创建订单明细信息
     *
     * @param product
     * @return
     * @author zhangjing
     */
    private Orderdetail createOrderDetail(Product product) {
        logger.info("**** " + product.getId() + " || " + product.getProductWeight());
        Orderdetail orderdetail = new Orderdetail();
        orderdetail.setProductID(Integer.parseInt(product.getId()));
        orderdetail.setProductName(product.getName());
        orderdetail.setPrice(product.getNowPrice());
        orderdetail.setNumber(product.getBuyCount());
        orderdetail.setTotal0(Double.toString(Double.parseDouble(product.getNowPrice()) * product.getBuyCount()));
        orderdetail.setSpecId(product.getBuySpecInfo().getId());
        orderdetail.setSpecInfo(product.getIntroduce());
        orderdetail.setGoodsStatus(product.getStatus());
        orderdetail.setGoodsImg(product.getImages());
        orderdetail.setFirstType(product.getFirstType());
        orderdetail.setSecontType(product.getSecondType());
        orderdetail.setDepositPrice(product.getDepositPrice());
        orderdetail.setBalancePrice(product.getBalancePrice());
        orderdetail.setGiftID(product.getGiftID());
        //orderdetail.setScore(product.getScore());//活的赠送的积分
        orderdetail.setPicture(product.getPicture());
        orderdetail.setProductWeight(product.getProductWeight());
        if (product.getBuySpecInfo() != null) {
            //按照规格计算
            orderdetail.setSpecInfo("规格一:" + product.getBuySpecInfo().getSpecSize() + "，规格二:" + product.getBuySpecInfo().getSpecColor());
            orderdetail.setSpecId(product.getBuySpecInfo().getId());
            orderdetail.setSpecSize(product.getBuySpecInfo().getSpecSize());
            orderdetail.setSpecColor(product.getBuySpecInfo().getSpecColor());
        }
        return orderdetail;
    }

    /**
     * 跳转立即支付页面
     *
     * @param model
     * @return
     * @throws Exception
     * @author zhangjing
     */
    @RequestMapping(value = "pay")
    @ResponseBody
    public Object pay(HttpServletRequest request, ModelMap model, HttpServletResponse response) throws Exception {
        logger.info("pay method start");

        Map<String, Object> result = new HashMap<String, Object>();
        String intoType = request.getParameter("intoType");
        String accountVoucher = request.getParameter("accountVoucher");
        String parentAmount = request.getParameter("parentAmount");
        String addressId = request.getParameter("addressId");
        String point = request.getParameter("point");
        String usedScore = request.getParameter("usedScore");
        logger.info("accountVoucher = " + accountVoucher + ",parentAmount = " + parentAmount +
                ",addressId = " + addressId + ",point = " + point + ",usedScore = " + usedScore);
        Account account = LoginUserHolder.getLoginAccount();    //得到登录用户的信息
        if (account == null || StringUtils.isBlank(account.getAccount())) {
            return page_toLoginRedirect;
        }
        //购物车进入支付
        if ("placPay".equals(intoType)) {
            List<OrderCustInputInfo> list = new ArrayList<OrderCustInputInfo>();
            String orderCust = request.getParameter("orderCust");
            if (!orderCust.isEmpty()) {
                JSONArray jsonArray = new JSONArray().fromObject(orderCust);
                list = (List) JSONArray.toCollection(jsonArray, OrderCustInputInfo.class);
            }

            //获得大订单信息
            Order parentOrder = (Order) redisCacheProvider.get(account.getId() + "parentOrder");

            // 校验商品限购和库存
            Map<String, String> checkResult = checkOrderNum(parentOrder, account);

            if (!"ok".equals(checkResult.get("result"))) {
                result.put("result", checkResult.get("result"));
                return result;
            }

            parentOrder.setSelectAddressID(addressId);
            Format format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            parentOrder.setCreatedate(format.format(new Date()));
            parentOrder.setAddTime(new Date());
            parentOrder.setAmount(parentAmount);
            if (!StringUtils.isBlank(usedScore)) {
                parentOrder.setIsUsePoint(1);
                parentOrder.setAmountExchangeScore(Integer.parseInt(usedScore));
            } else {
                parentOrder.setIsUsePoint(0);
                parentOrder.setAmountExchangeScore(0);
            }
            //设置抵扣券使用
            if (!StringUtils.isBlank(accountVoucher)&&!"-1".equals(accountVoucher)) {
                parentOrder.setDeductibleId(accountVoucher.split(",")[0]);
                parentOrder.setDeductible(accountVoucher.split(",")[1]);
            }

            List<Order> sonOrderList = parentOrder.getOrders();    //子订单信息
            for (Order sonOrder : sonOrderList) {
                for (OrderCustInputInfo orderCustInputInfo : list) {
                    logger.info(orderCustInputInfo.toString());
                    if (sonOrder.getOrderCode().equals(orderCustInputInfo.getOrderCode())) {
                        sonOrder.setCarry(orderCustInputInfo.getExpressCode());     //运送方式
                        sonOrder.setExpressCode(orderCustInputInfo.getExpressCode());
                        sonOrder.setExpressName(orderCustInputInfo.getExpressName());
                        sonOrder.setFee(orderCustInputInfo.getFee());
                        sonOrder.setOtherRequirement(orderCustInputInfo.getOtherRequirement());
                        //sonOrder.setPtotal(orderCustInputInfo.getPtotal());
                        sonOrder.setAmount(orderCustInputInfo.getPtotal());
                        //sonOrder.setAdvancePrice(orderCustInputInfo.getPtotal());
                        sonOrder.setIsSaleorder(0);
                        //优惠券信息
                        if (null != orderCustInputInfo.getCouponsId() && !"".equals(orderCustInputInfo.getCouponsId())) {
                            sonOrder.setCouponsId(orderCustInputInfo.getCouponsId());
                            sonOrder.setCoupons(orderCustInputInfo.getCouponValue());
                            sonOrder.setIsUserCoupons(1);
                        } else {
                            sonOrder.setIsUserCoupons(0);
                        }
                        sonOrder.setRefundStatus("0");      //退款状态  0-未退款 1--退款
                    }
                }
            }
            insertAndPay(parentOrder, model, response,parentAmount);
        }
        //待补款进入支付
        else if ("placAdd".equals(intoType)&&!"-1".equals(accountVoucher)) {
            Order addOrder = (Order) redisCacheProvider.get(account.getId() + "addOrder");
            addOrder.setAmount(parentAmount);
            addOrder.setSelectAddressID(addressId);
            if (StringUtils.isNotBlank(accountVoucher)) {
                addOrder.setDeductibleId(accountVoucher.split(",")[0]);    //抵扣券
                addOrder.setDeductible(accountVoucher.split(",")[1]);
            }
            redisCacheProvider.put(account.getId() + "mainOrder", addOrder);
        }
        result.put("result", "ok");
        return result;
    }


    private Map<String, String> checkOrderNum(Order parentOrder, Account account) {

        Map<String, String> result = new HashMap<String, String>();

        result.put("result", "ok");


        for (Order order : parentOrder.getOrders()) {

            List<Orderdetail> OrderdetailList = order.getOrderdetail();

            // 下单判断库存 及 限购
            for (Orderdetail orderdetail : OrderdetailList) {
                String specId = orderdetail.getSpecId();
                Integer productId = orderdetail.getProductID();
                Integer qty = orderdetail.getNumber();

                // 当前用户购买数量
                Integer account_product_xgslValue = 0;
                String account_product_xgsl = account.getId() + ManageContainer.account_product_xgsl + productId;
                if (redisCacheProvider.get(account_product_xgsl) != null) {
                    account_product_xgslValue = Integer.valueOf(redisCacheProvider.get(account_product_xgsl).toString());
                }
                // 限购数量
                Integer product_spxgValue = 0;
                String product_spxg = productId + ManageContainer.product_xgsl;
                if (redisCacheProvider.get(product_spxg) != null) {
                    product_spxgValue = Integer.valueOf(redisCacheProvider.get(product_spxg).toString());
                }

                //查询限购 约定限购数量为0时不限购
                if (product_spxgValue != 0) {
                    if (qty + account_product_xgslValue > product_spxgValue) {
                        result.put("result", "很抱歉，您已超过商品的最大购买数量！");
                        return result;
                    }
                }

                // 下单库存
                Integer product_xdkcValue = 0;
                if (StringUtils.isNotEmpty(specId)) {
                    String product_xdkc = productId + ManageContainer.product_xdkc + specId;
                    product_xdkcValue = Integer.valueOf(redisCacheProvider.get(product_xdkc).toString());
                }


                /**
                 * 检查内存库存是否已超卖，如果超库存不足，则提醒用户
                 */
                if (qty > product_xdkcValue) {
                    result.put("result", "很抱歉，商品库存不足！");
                    return result;
                }
            }
        }

        return result;
    }

    /**
     * 创建订单，并跳转到支付页面让用户进行支付
     * @param parentOrder
     * @param model
     * @param response
     * @param parentAmount 订单实际支付的金额
     * @throws Exception
     */
    private void insertAndPay(Order parentOrder, ModelMap model, HttpServletResponse response,String parentAmount) throws Exception 
    {
        response.setContentType("application/xml;charset=utf-8");
        logger.info("大订单ID：" + parentOrder.getOrderCode());
        logger.info("SelectAddressID = " + parentOrder.getSelectAddressID());
        //无地址信息，视为非法请求
        if (StringUtils.isBlank(parentOrder.getSelectAddressID())) {
            throw new NullPointerException("非法请求！");
        }
        
        //创建订单并插入到数据库
        Order order = orderService.createOrder(parentOrder,parentAmount);
		/*
		 * 创建订单后，在用户购物车中剔除本次选中商品
		 */
        CartInfo cartInfo = getMyCart();
        List<Order> sonOrderList = parentOrder.getOrders();        //所有子订单
        logger.info("包含子订单个数：" + sonOrderList.size());
        for (Order sonOrder : sonOrderList) 
        {
            List<Orderdetail> orderdetail = sonOrder.getOrderdetail();
            for (int i = 0; i < orderdetail.size(); i++) 
            {
                if (cartInfo != null && cartInfo.getProductList() != null)
                {
                    for (Iterator<Product> it = cartInfo.getProductList().iterator(); it.hasNext(); ) 
                    {
                        Product p = it.next();
                        if (p.getId().equals(Integer.toString(orderdetail.get(i).getProductID()))) 
                        {
                            it.remove();
                            //重新计算总支付金额
                            cartInfo.totalCacl();
                        }
                    }
                }
            }
        }
        Account account = LoginUserHolder.getLoginAccount();    //得到登录用户的信息
        if (account == null) 
        {
            redisCacheProvider.put("myCart", cartInfo);
        } 
        else 
        {
            redisCacheProvider.put("user_" + account.getId() + "Cart", cartInfo);
        }
        logger.info("into plac_pay.ftl");
        //radis中删除本次下单信息
        //redisCacheProvider.remove(account.getId() + "parentOrder");
        redisCacheProvider.put(account.getId() + "mainOrder", order);
    }
	

    /**
     * @param model
     * @return
     * @author zhangjing
     */
    @RequestMapping(value = "plac_pay", method = RequestMethod.POST)
    public String toPlacPay(ModelMap model) {
        //查询帐户余额
        Account account = getLoginAccount();
        if (account == null || StringUtils.isBlank(account.getAccount())) {
            return page_toLoginRedirect;
        }
        Order mainOrder = (Order) redisCacheProvider.get(account.getId() + "mainOrder");
        AccountFinance aFinance = accountFinanceService.queryAccountFinanceByUserId(account.getId());
        if (aFinance != null) {
            model.addAttribute("accountAmount", aFinance.getAmount());
        }
        model.addAttribute("mainOrder", mainOrder);
        //redisCacheProvider.remove("mainOrder");
        //帮助支持列表
        Help help = new Help();
        help.setStatus("y");
        List<Help> helpList = helpService.selectList(help);
        model.addAttribute("helpList", helpList);
        return "order/plac_pay";
    }

    /**
     * 进入补款订单确认页面
     *
     * @param model
     * @return
     * @author zhangjing
     */
    @RequestMapping("plac_add")
    public String toAddPay(ModelMap model, @ModelAttribute("order") Order order1) {
        //获得用户信息
        Account account = getLoginAccount();
        if (account == null || StringUtils.isBlank(account.getAccount())) {
            return page_toLoginRedirect;
        }
        String orderId = RequestHolder.getRequest().getParameter("id");
        logger.info("plac_add:orderId = " + orderId);
        //根据id查询子订单信息
        Order order = orderService.selectById(orderId);
        order.setBusinessShippingList(orderBusinessShippingService.queryOrderBusinessShipping(order.getBusinessId()));
        //优惠券
        List<AccountCoupon> accountCouponList = accountCouponService.selectAccountCouponList(account.getId(), order.getBusinessId());
		/*AccountCoupon accountCoupon = new AccountCoupon();
		accountCoupon.setId("MF0001");
		accountCoupon.setCouponName("未使用优惠券");
		accountCoupon.setCouponValue("0");
		accountCouponList.add(0, accountCoupon);*/
        order.setAccountCouponList(accountCouponList);
        order.setOrderCodeView(order.getOrderCode().substring(8));
        //补款时，将子订单尾款赋值于订单金额字段
        order.setAmount(order.getBalancePrice());
        //平台抵扣券
        List<AccountCoupon> accountVoucherList = accountCouponService.selectAccountVoucherList(account.getId());
		/*AccountCoupon accountVoucher = new AccountCoupon();
		accountVoucher.setId("MFPT0001");
		accountVoucher.setCouponName("未使用抵扣券");
		accountVoucher.setCouponValue("0");
		accountVoucherList.add(0, accountVoucher);*/
        order.setAccountVoucherList(accountVoucherList);
        //根据子订单查询订单详情信息
        Orderdetail qayOrderDetail = new Orderdetail();
        qayOrderDetail.setOrderID(orderId);
        Orderdetail orderDetail = orderdetailService.selectOne(qayOrderDetail);
        logger.info("orderDetail.getPicture() = " + orderDetail.getPicture());
		/*
		 * 加载指定商品的规格信息
		 */
        if (StringUtils.isNotBlank(orderDetail.getSpecId())) {
            //根据选中的规格id查询获取规格信息
            Spec spec = specService.selectById(orderDetail.getSpecId());
            if (spec == null) {
                throw new NullPointerException("根据指定的规格" + orderDetail.getSpecId() + "查询不到任何数据!");
            }
            //将匹配的图片赋值
            orderDetail.setPicture(order.getPicture());
            //将匹配的规格信息赋值
            orderDetail.setSpecSize(spec.getSpecSize());
            ;
            orderDetail.setSpecColor(spec.getSpecColor());
        }
        model.addAttribute("orderDetail", orderDetail);
        //用户积分
        int rank = 0;
        AccountFinance accountFinance = accountFinanceService.queryAccountFinanceByUserId(account.getId());
        if (accountFinance != null) {
            rank = accountFinance.getRank();
        }
        model.addAttribute("rank", rank);
        //地址列表
        Address address = new Address();
        address.setAccountId(account.getId());
        List<Address> addressList = addressService.selectList(address);
        logger.info("用户" + account.getAccount() + "共有" + addressList.size() + "个地址");
        model.addAttribute("addressList", addressList);
        model.addAttribute("order", order);
        redisCacheProvider.put(account.getId() + "addOrder", order);
        return "order/plac_add";
    }

    /**
     * 点击立即支付按钮，执行订单状态信息修改操作
     *
     * @author zhangjing
     */
    @RequestMapping("immediatelyPay")
    public String immediatelyPay() {
        logger.info("immediately pay start....");
        String orderid = RequestHolder.getRequest().getParameter("orderid");
        Account account = getLoginAccount();

        Orderlog orderlog = new Orderlog();
        orderlog.setOrderid(orderid);//订单ID
        orderlog.setAccount(account.getAccount());//操作人账号
        orderlog.setContent("支付成功");//日志内容
        orderlog.setAccountType(Orderlog.orderlog_accountType_p);
        //orderService.updateOrderStatusByConfirm(orderlog);
        logger.info("pay success....");
        return "order/paySuccess";
    }

    /**
     * 购物车跳转立即支付页面
     *
     * @param model
     * @return 跳转支付成功页面
     * @author zhangjing
     */
    @RequestMapping(value = "toPay")
    @ResponseBody
    public String toPay(ModelMap model) {
        //获取登录用户信息，若获取null，则跳转登陆页面
        Account account = getLoginAccount();
        if (account == null) {
            return page_toLogin;
        }
        //需要先判断下订单是否已经支付过了
        //获取前台传递的订单号
        String orderCode = RequestHolder.getRequest().getParameter("orderCode");
        //获取前台传递的支付宝金额
        String payBaoAmount = RequestHolder.getRequest().getParameter("payBaoAmount");
        //获取前台传递的使用余额
        String payAccountAmount = RequestHolder.getRequest().getParameter("payAccountAmount");
		/*
		 * 获取前台传递的支付方式
		 * amtWay : 账户余额
		 * baoWay ： 支付宝
		 * allWay ： 账户余额 + 支付宝
		 */
        String payWay = RequestHolder.getRequest().getParameter("payWay");

        logger.info("orderCode = " + orderCode +
                ",payBaoAmount = " + payBaoAmount +
                ",payAccountAmount = " + payAccountAmount +
                ",payWay = " + payWay);
        //若获取前台订单号为空，则抛出异常（“订单号获取失败！”）
        if (StringUtils.isBlank(orderCode)) {
            throw new IllegalArgumentException("订单号获取失败！");
        }
        //根据订单号查询出父订单 订单信息
        Order parentOrder = new Order();
        parentOrder.setOrderCode(orderCode);
        parentOrder = orderService.selectOne(parentOrder);
        //logger.info("orderId = " + order.getId());

		/*
		 * 查询该单配送方式，获取配送地址，供支付成功页面展示
		 * 并且进行支付成功后的一系列数据更新及插入操作
		 * 因orderService.updateInfoAfterPay方法参数为父订单
		 * 所以第一次付款订单和补款的预售单支付成功后更新相关信息传值有所不同
		 * 	第一次付款订单 --> 父订单
		 * 	补款的预售单 --> 子订单
		 */
        //根据父订单号查询获得子订单list
        Order qrySonOrder = new Order();
        qrySonOrder.setOrderCode(orderCode);
        List<Order> sonOrderList = orderService.selectSonOrderList(qrySonOrder);
        // 检查余额 积分 优惠券使用情况
        boolean checkResult = checkAmtAndCoupon(sonOrderList, parentOrder, account, payAccountAmount);
        if (!checkResult) {
            return "orderErr";
        }
        //获取session
        HttpSession session = RequestHolder.getRequest().getSession();
        session.setAttribute("orderCode", orderCode);
        //订单总金额
        session.setAttribute("amount", parentOrder.getAmount());
        //商品总金额
        session.setAttribute("ptotal", parentOrder.getPtotal());
        //只有账户余额方式支付
        if ("amtWay".equals(payWay)) {
            //扣减客户账户余额,sql里进行的运算 -_-!
            accountFinanceService.cutAccountAmount(account.getId(), payAccountAmount);
            // 更新支付后的订单信息
            orderService.updateInfoAmtWayPay(parentOrder, sonOrderList, payWay);
        }//只有支付宝方式支付
        else if ("baoWay".equals(payWay)) {
            session.setAttribute("payBaoAmount", payBaoAmount);
            //创建支付信息实体，供调用支付接口使用
            PayInfo payInfo = createPayInfo(parentOrder);
            payInfo.setWIDprice(Double.parseDouble(payBaoAmount));        //支付宝支付金额
            session.setAttribute("payInfo", JSON.toJSONString(payInfo));
            //跳转支付宝支付页面
            return "alipayapi";
        }//账户余额+支付宝方式支付
        else if ("allWay".equals(payWay)) {
            //将账户支付余额传递支付成功页面展示
            session.setAttribute("payAccountAmount", payAccountAmount);
            session.setAttribute("payWay", "allWay");
            //后调用支付宝支付
            PayInfo payInfo = createPayInfo(parentOrder);
            payInfo.setWIDprice(Double.parseDouble(payBaoAmount));
            session.setAttribute("payInfo", JSON.toJSONString(payInfo));
            return "alipayapi";
        }//支付方式获取失败
        else {
            throw new IllegalArgumentException("支付方式获取失败！");
        }
        return "paySuccess";
    }

    private boolean checkAmtAndCoupon(List<Order> sonOrderList, Order parentOrder, Account account, String payAccountAmount) {

        // 获取用户余额积分
        AccountFinance accountFinance = accountFinanceService.queryAccountFinanceByUserId(account.getId());
        // 判断余额是否超过
        //TODO review?
        if (payAccountAmount != null) {
            if (Float.valueOf(payAccountAmount) > Float.valueOf(accountFinance.getAmount())) {
                return false;
            }
        }
        // 判断积分是否超出
        if (parentOrder.getAmountExchangeScore() > Integer.valueOf(accountFinance.getPoints())) {
            return false;
        }

        // 判断平台折扣券是否使用
        if (StringUtils.isNotBlank(parentOrder.getDeductibleId())) {
            AccountDeductibleVoucher accountDeductibleVoucher = new AccountDeductibleVoucher();
            accountDeductibleVoucher.setId(parentOrder.getDeductibleId());
            accountDeductibleVoucher.setUserId(account.getId());
            AccountDeductibleVoucher result = accountDeductibleVoucherService.selectOne(accountDeductibleVoucher);
            if (result.getStatus() == 2) {
                return false;
            }
        }

        // 判断商家优惠券是否使用
        for (Order sonOrder : sonOrderList) {
            if (StringUtils.isNotBlank(sonOrder.getCouponsId())) {
                AccountCoupon accountCoupon = new AccountCoupon();
                accountCoupon.setId(sonOrder.getCouponsId());
                accountCoupon.setUserId(account.getId());
                AccountCoupon result = accountCouponService.selectOne(accountCoupon);
                if (result.getStatus() == 2) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * 点击我的订单页面的未付款的订单进行付款操作,则跳转到付款页面进行付款
     *
     * @return
     */
    @RequestMapping("toOrderPay")
    public String toOrderPay() {
        if (getLoginAccount() == null) {
            return page_toLogin;
        }
        String id = RequestHolder.getRequest().getParameter("id");
        if (StringUtils.isBlank(id)) {
            throw new NullPointerException();
        }
        Order queryOrder = new Order();
        queryOrder.setId(id);
        Order order = orderService.selectOne(queryOrder);
        logger.info("orderId=" + order.getId());
        boolean ispayCreate = orderpayService.isOrderpayCreate(order.getId());
        logger.debug("立即付款torderpay是否已创建：" + ispayCreate);
        if (!ispayCreate) {
            //创建支付记录对象
            Orderpay orderpay = new Orderpay();
            orderpay.setOrderid(order.getId());
            orderpay.setPaystatus(Orderpay.orderpay_paystatus_n);

            orderpay.setPayamount(Double.valueOf(order.getAmount()));
            orderpay.setPaymethod(Orderpay.orderpay_paymethod_alipayescow);
            int orderpayID = orderpayService.insert(orderpay);
            logger.error("orderpayID=" + orderpayID);
            order.setOrderpayID(String.valueOf(orderpayID));
        }

        //查询配送地址信息
        RequestHolder.getRequest().setAttribute("payInfo", createPayInfo(order));

        return "order/alipayapi";
    }


    void copy(File f1, File f2) {//f1 源文件路径  f2目标路径   最后把f2 insert 到数据库就不写了
        try {
            // 建立相关的字节输入流
            FileInputStream fr = new FileInputStream(f1); // 通过打开一个到实际文件的连接来创建一个
            // FileInputStream，该文件通过文件系统中的路径名

            // 创建一个向具有指定名称的文件中写入数据的输出文件流。
            FileOutputStream fw = new FileOutputStream(f2);
            byte buffer[] = new byte[1]; // 声明一个byte型的数组，数组的大小是512个字节
            while (fr.read(buffer) != -1) { // read()从此输入流中读取一个数据字节，只要读取的结果不！=-1就执行while循环中的语句块
                fw.write(buffer); //write(byte[] b)将 b.length 个字节从指定字节数组写入此文件输出流中。
            }
            fw.close();// 关闭此文件输出流并释放与此流有关的所有系统资源。
            fr.close();
            System.out.println("文件" + f1.getName() + "里的内容已拷贝到文件"
                    + f2.getName() + "中！");
        } catch (IOException ioe) {
            System.out.println(ioe);
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    /**
     * 支付成功后进行评价,转到评论页面
     *
     * @return
     * @throws Exception
     */
//    @RequestMapping("rate")
//    public String rate(@ModelAttribute("e") Order e, ModelMap model) throws Exception {
//        Account acc = getLoginAccount();
//        if (acc == null) {
//            return page_toLogin;
//        }
//        String productID = RequestHolder.getRequest().getParameter("productID");
//        String orderid = RequestHolder.getRequest().getParameter("orderid");
//        if (StringUtils.isBlank(orderid) && StringUtils.isBlank(productID)) {
//            throw new NullPointerException("参数异常！");
//        }
//		
//		/*
//		 * 用户可以对每个订单项对应的商品进行评价
//		 */
//        Orderdetail orderdetail = new Orderdetail();
//        orderdetail.setOrderID(orderid);
////		orderdetail.setIsComment(Orderdetail.orderdetail_isComment_n);
//        List<Orderdetail> list = orderdetailService.selectList(orderdetail);
//        List<Orderdetail> list1 = new ArrayList<Orderdetail>();
//        if (list != null && list.size() > 0) {
//            for (Orderdetail orderdetail2 : list) {
//                if (String.valueOf(orderdetail2.getProductID()).toString().equals(productID)) {
//                    list1.add(orderdetail2);
//                }
//            }
//        }
//        e.setRateOrderdetailList(list1);
//        e.setId(orderid);
//        if (e.getRateOrderdetailList() != null && e.getRateOrderdetailList().size() == 0) {
//            e.setRateOrderdetailList(null);
//        }
//
//        //加载商品信息
////		product = productService.selectById(productID);
//        //加载以往用户的评价信息
//        Comment comment = new Comment();
//        comment.clear();
//        comment.setAccount(acc.getId());
//        comment.setProductID(productID);
//        comment.setOrderID(orderid);
//        Comment comment1 = commentService.selectOne(comment);
//        if (comment1 == null) {
//            logger.error("还没有评价");
//        } else {
//            logger.error("已经评价过了");
//            e.setRateOrderdetailList(null);
//        }
//
//        //加载指定商品的评论列表
////		Comment commentParam = new Comment();
////		commentParam.setProductID(Integer.valueOf(productID));
////		selectCommentList(commentParam);
//        model.addAttribute("e", e);
//        CartInfo cartInfo = null;
//        List<Product> productList = new ArrayList<Product>();
//        cartInfo = (CartInfo) redisCacheProvider.get("user_" + acc.getId() + "Cart");
//        if (cartInfo != null) {
//            productList = cartInfo.getProductList();
//        } else {
//            cartInfo = new CartInfo();
//        }
//        int productCount = productService.selectProductCount();
//        model.addAttribute("cartInfo", cartInfo);
//        model.addAttribute("productCount", productCount);
//        model.addAttribute("productList", productList);
//        return "order/rate";
//    }

    DecimalFormat df = new DecimalFormat("0.00");

    /**
     * 创建支付宝的付款信息对象
     *
     * @param order
     */
    private PayInfo createPayInfo(Order order) {
        if (order == null) {
            throw new NullPointerException("参数不能为空！请求非法！");
        }

        PayInfo payInfo = new PayInfo();
        String www = systemSetting.getWww();

        /**
         * 解决由于本地和线上正式环境提交相同的商户订单号导致支付宝出现TRADE_DATA_MATCH_ERROR错误的问题。
         * 本地提交的商户订单号前缀是test开头，正式环境提交的就是纯粹的支付订单号
         */
        if (www.startsWith("http://127.0.0.1") || www.startsWith("http://localhost")) {
            payInfo.setWIDout_trade_no("test" + order.getOrderCode());
        } else {
            payInfo.setWIDout_trade_no(order.getOrderCode());
        }
        payInfo.setWIDsubject(order.getProductName());
        payInfo.setWIDprice(Double.valueOf(order.getAmount()));
        payInfo.setWIDbody(order.getRemark());
        payInfo.setShow_url(systemSetting.getWww() + "/order/orderInfo.html?id=" + order.getId());
        payInfo.setLogistics_fee(Double.valueOf(order.getFee()));
        payInfo.setLogistics_type(order.getExpressCode());
        return payInfo;
    }

 

    /**
     * 确认订单信息
     *
     * @return
     */
    @RequestMapping("confirmOrder")
    public String confirmOrder(ModelMap model) {
        logger.error("confirmOrder..");
        Account acc = getLoginAccount();
        if (acc == null || StringUtils.isBlank(acc.getAccount())) {
//			getSession().getAttribute(FrontContainer);
            return page_toLoginRedirect;
        }

        //检查购买的商品是否超出可购买的库存数
        CartInfo cartInfo = getMyCart();
        if (cartInfo == null) {
            throw new NullPointerException("非法请求");
        }

//        for (int i = 0; i < cartInfo.getProductList().size(); i++) {
//            Product product = cartInfo.getProductList().get(i);
//            ProductStockInfo stockInfo = SystemManager.getInstance().getProductStockMap().get(product.getId());
//            if (stockInfo == null) {
//                //商品已卖完或已下架，请联系站点管理员!
//                throw new RuntimeException("商品已卖完或已下架，请联系站点管理员!");
//            } else if (stockInfo.getStock() < product.getBuyCount()) {
//                //购买的商品数超出库存数
//                throw new RuntimeException("商品已卖完或已下架，请联系站点管理员!");
//            }
//        }

        //加载配送信息
        Address add = new Address();
        add.setAccountId(acc.getAccount());
        List<Address> addressList = addressService.selectList(add);
        cartInfo.setAddressList(addressList);
        if (addressList != null && addressList.size() > 0) {
//			boolean exist = false;
            for (int i = 0; i < addressList.size(); i++) {
                Address addItem = addressList.get(i);
                if (StringUtils.isNotBlank(addItem.getIsdefault()) && addItem.getIsdefault().equals("y")) {
                    cartInfo.setDefaultAddessID(addItem.getId());
                    break;
                }
            }
        }
        model.addAttribute("myCart", cartInfo);
        model.addAttribute("expressList", loadExpress().values());
        return "order/confirmOrder";
    }
    /**
	 * 加载物流列表
	 */
	private Map<String, Express> loadExpress(){
		List<Express> expressList = expressService.selectList(new Express());
        Map<String, Express> expressMap = Maps.newHashMap();
		if(expressList!=null && expressList.size()>0){
			for(int i=0;i<expressList.size();i++){
				Express item = expressList.get(i);
				expressMap.put(item.getCode(), item);
			}
		}
        return expressMap;
	}
    /**
     * 支付成功后，回调请求跳转到的页面
     *
     * @return
     */
    @RequestMapping(value = "paySuccess")
    public String paySuccess(ModelMap model) {
        Account acc = getLoginAccount();
        logger.error("paySuccess...");
        HttpSession session = RequestHolder.getRequest().getSession();
        System.out.println("yyyyyyy" + session.getAttribute("payAccountAmount"));
        double payAccountAmount = 0;
        //String orderCode=String.valueOf(session.getAttribute("orderCode"));
        String orderCode = "1458447999223843828";
        boolean orderPayStatus = orderService.payOrderStatus(orderCode);
        System.out.println("orderPayStatus==============" + orderPayStatus);
        List<Orderdetail> orderdetailList1 = new ArrayList<Orderdetail>(JSON.parseArray((String) session.getAttribute("orderdetailList"), Orderdetail.class));
        session.setAttribute("orderdetailList1", orderdetailList1);
        Order order = JSON.parseObject((String) session.getAttribute("order"), Order.class);
        session.setAttribute("order", order);
        Ordership orderShip = JSON.parseObject((String) session.getAttribute("orderShip"), Ordership.class);
        session.setAttribute("orderShip", orderShip);
        if (session.getAttribute("payAccountAmount") != null) {
            payAccountAmount = Double.parseDouble(String.valueOf(session.getAttribute("payAccountAmount")));
        } else {
            payAccountAmount = Double.parseDouble(order.getAccount());
        }
        java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
        model.put("payAccountAmount", df.format(payAccountAmount));
        if (orderPayStatus) {
            //支付成功扣库存,刷新限购数量
            Order qrySonOrder = new Order();
            qrySonOrder.setOrderCode(orderCode);
            List<Order> sonOrderList = orderService.selectSonOrderList(qrySonOrder);
            Orderdetail orderdetail = new Orderdetail();
            List<Orderdetail> orderdetailList = new ArrayList<Orderdetail>();
            System.out.println("sonOrderList==============" + sonOrderList.size());
            for (Order order2 : sonOrderList) {
                orderdetail.setOrderID(order2.getId());
                List<Orderdetail> list = orderdetailService.selectList(orderdetail);
                orderdetailList.addAll(list);
            }
            System.out.println("orderdetailList==============" + orderdetailList.size());
            for (Orderdetail orderDetail : orderdetailList) {
                //刷新缓存支付库存
                String specId = orderDetail.getSpecId();
                String product_zfkc = orderDetail.getProductID() + ManageContainer.product_zfkc + specId;
                Integer product_zfkcValue = Integer.valueOf(redisCacheProvider.get(product_zfkc).toString());
                redisCacheProvider.put(product_zfkc, product_zfkcValue - orderDetail.getNumber());
                //刷新数据库的支付库存
                Spec s = new Spec();
                s.setSpecStock(String.valueOf(product_zfkcValue));
                s.setId(specId);
                specService.update(s);

                //支付成功刷新缓存客户购买数量
                String account_product_xgsl = acc.getAccountId() + ManageContainer.account_product_xgsl + orderDetail.getProductID();
                if (redisCacheProvider.get(account_product_xgsl) == null) {
                    redisCacheProvider.put(account_product_xgsl, orderDetail.getNumber());
                } else {
                    Integer account_product_xgslValue = Integer.valueOf(redisCacheProvider.get(account_product_xgsl).toString());
                    redisCacheProvider.put(product_zfkc, account_product_xgslValue + orderDetail.getNumber());
                }

//				//支付成功刷新数据库的客户的购买数量
//				AccountBuy accountBuyParam = new AccountBuy();
//				accountBuyParam.setAccountId(acc.getId());
//				accountBuyParam.setProductId(orderDetail.getProductID());
//				AccountBuy accountBuy = accountBuyService.selectOne(accountBuyParam);
//				if(accountBuy==null)
//				{
//					accountBuy = new AccountBuy();
//					accountBuy.setAccountId(acc.getId());
//					accountBuy.setProductId(orderDetail.getProductID());
//					accountBuy.setBuyNum(orderDetail.getNumber());
//					accountBuyService.insert(accountBuy);
//				}
//				else
//				{
//					accountBuy.setBuyNum(accountBuy.getBuyNum()+orderDetail.getNumber());
//					accountBuyService.update(accountBuy); 
//				}
//				
                //刷新销量
                Product productParam = productService.selectById(String.valueOf(orderDetail.getProductID()));
                productParam.setSellcount(productParam.getSellcount() + orderDetail.getNumber());
                productService.update(productParam);
            }
            return "order/paySuccess";
        } else {
            return "order/paySuccess";
        }
    }

    /**
     * 得到支付状态
     *
     * @return
     */
    @RequestMapping("getPayStatus")
    public void getPayStatus(HttpServletResponse response) {
        HttpSession session = RequestHolder.getRequest().getSession();
        String orderCode = String.valueOf(session.getAttribute("orderCode"));
        boolean orderPayStatus = orderService.payOrderStatus(orderCode);
        response.setContentType("text/html;charset=UTF-8");
        try {
            if (orderPayStatus) {
                response.getWriter().write("1");
                return;
            }
            response.getWriter().write("0");
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 确认成功时跳转
     *
     * @param model
     * @return
     */
    @RequestMapping("paySuccessAgain")
    public String paySuccessAgain(ModelMap model) {
        HttpSession session = RequestHolder.getRequest().getSession();
        String orderCode = String.valueOf(session.getAttribute("orderCode"));
        boolean orderPayStatus = orderService.payOrderStatus(orderCode);
        if (orderPayStatus) {
            return "order/paySuccess";
        } else {
            return "order/paySuccess";
        }
    }


    /**
     * 快递费计算
     */
    @RequestMapping("getShiping")
    @ResponseBody
    public Object getShiping(HttpServletRequest request, ModelMap model, HttpServletResponse response) throws Exception {
    	
    	// 返回值
    	Map<String,Object> result = new HashMap<String, Object>();
        //获取前台传递的子订单号
        String orderCodeView = request.getParameter("sonorderCode");
        logger.info("orderCodeView from ftl is " + orderCodeView);
        //获取前台传递的选中运送方式id
        String shippingId = request.getParameter("shippingId");
        //获取前台传递的选中地址id
        String addressId = request.getParameter("addressId");
        //运费价格
        double shipMoney = 0;
        //得到登录用户的信息
        Account account = LoginUserHolder.getLoginAccount();
        
        if (account == null || StringUtils.isBlank(account.getAccount())) {
       	 	result.put("result", "needLogin");
            return JsonUtil.objectToJson(result);
        }
        //从redis中获取父订单
        Order parentOrder = (Order) redisCacheProvider.get(account.getId() + "parentOrder");
        //取得父订单中子订单list
        List<Order> sonOrderList = parentOrder.getOrders();
		 /*
		  * 获得选中子订单信息
		  * 遍历父订单获取的所有子订单，与前台传递的子订单号比较
		  * 若相等，则匹配上子订单
		  */
        Order sonOrder = new Order();
        for (int i = 0; i < sonOrderList.size(); i++) {
            Order order = sonOrderList.get(i);
            if (order.getOrderCodeView().equals(orderCodeView)) {
            	sonOrder = order;
                break;
            }
        }
        logger.info("选中的子订单号为：" + sonOrder.getOrderCode());

        //获得选中快递方式信息
        List<BusinessShipping> shipList = sonOrder.getBusinessShippingList();
        BusinessShipping shipping = new BusinessShipping();
        for (int i = 0; i < shipList.size(); i++) {
        	
            BusinessShipping s = shipList.get(i);
            if (s.getShippingId().equals(shippingId)) {
                shipping = s;
                break;
            }
        }
        logger.info("选中的快递为：" + shipping.getId());
        
        //获得选中运送地址
        Address address = addressService.selectById(addressId);
        logger.info("address.getProvince() = " + address.getProvince());
        //获得运费详情  用于计算
        BusinessShippingDetail businessShippingDetail = new BusinessShippingDetail();
        List<BusinessShippingDetail> shipdetailList = shipping.getBsdList();
        for (BusinessShippingDetail shippingDetail : shipdetailList) {
            logger.info("shippingDetail.getProvinceId() = " + shippingDetail.getProvinceId());
            if (shippingDetail.getProvinceId().equals(address.getProvince())) {
                businessShippingDetail = shippingDetail;
                break;
            }
        }
		 /*
		  * 如果运送方式不支持客户选中地址，则直接返回0运费
		  */
        if (StringUtils.isNotBlank(businessShippingDetail.getId())) {
        	
        	// 默认快递  运费为0
            if(shipping.getIsDefault()==1) {
            	 result.put("result", shipMoney);
                 return JsonUtil.objectToJson(result);
            } 
            
            // 默认配送快递明细
            BusinessShippingDetail defaultShippingDetail = new BusinessShippingDetail();
            // 默认地址始终是第一个
            if(shipList.get(0).getIsDefault()==1) {
            	BusinessShipping defaultShipping = shipList.get(0);
            	//获得默认快递运费详情  用于计算
                List<BusinessShippingDetail> defaultShippingdetailList = defaultShipping.getBsdList();
                for (BusinessShippingDetail shippingDetail : defaultShippingdetailList) {
                    if (shippingDetail.getProvinceId().equals(address.getProvince())) {
                    	defaultShippingDetail = shippingDetail;
                    	 break;
                    }
                }
            }
            
            //商品所有重量
            double allWeight = 0;
            List<Orderdetail> OrderdetailList = sonOrder.getOrderdetail();
            for (Orderdetail orderdetail : OrderdetailList) {
                double productWeight = 0;
                if (orderdetail.getProductWeight() != null && orderdetail.getProductWeight() != "") {
                	productWeight = Double.parseDouble(orderdetail.getProductWeight()); //单个商品重量
                }
                double pCnt = orderdetail.getNumber();  //商品数量
                allWeight = productWeight + productWeight * pCnt;
            }
            
            // 默认快递 运费
            double defaultFee = 0;
            if(StringUtils.isNotBlank(defaultShippingDetail.getId())) {
            	 //商品重量向上取整
                double defaultFirstHeavy = Double.parseDouble(businessShippingDetail.getFirstHeavy());//商品首重
                if (allWeight <= defaultFirstHeavy) {
                    //商品重量小于等于首重。价格取首重价格
                	defaultFee = defaultShippingDetail.getFristPrice();
                } else {
                    double weight = allWeight - defaultFirstHeavy;
                    double setpHeavy = Double.parseDouble(defaultShippingDetail.getStepHeavy());
                    double hmg = weight / setpHeavy; //快递规格
                    int cnt = (int) Math.ceil(hmg);
                    defaultFee = defaultShippingDetail.getFristPrice();
                    defaultFee = defaultFee + (cnt * businessShippingDetail.getStepPrice());
                }
                
            }
            // 当前选中快递 运费
            double currentFee = 0;
            //商品重量向上取整
            double firstHeavy = Double.parseDouble(businessShippingDetail.getFirstHeavy());//商品首重
            if (allWeight <= firstHeavy) {
                //商品重量小于等于首重。价格取首重价格
            	currentFee = businessShippingDetail.getFristPrice();
            } else {
                double weight = allWeight - firstHeavy;
                if(businessShippingDetail.getStepHeavy()!=null) {
                	double setpHeavy = Double.parseDouble(businessShippingDetail.getStepHeavy());
                	double hmg = weight / setpHeavy; //快递规格
                    int cnt = (int) Math.ceil(hmg);
                    currentFee = businessShippingDetail.getFristPrice();
                    currentFee = currentFee + (cnt * businessShippingDetail.getStepPrice());
                } 
            }
            
            shipMoney = currentFee - defaultFee;
            if(shipMoney<0) {
            	shipMoney = 0;
            }
            result.put("result", shipMoney);
            return JsonUtil.objectToJson(result);
        } else {
        	result.put("result", "noMatch");
            return JsonUtil.objectToJson(result);
        }
    }



    /**
     * 商家优惠券使用
     */
    @RequestMapping("getCoupon")
    @ResponseBody
    public Object getCoupon(HttpServletRequest request, ModelMap model, HttpServletResponse response) throws Exception {
    	 
    	 // 获取当前登录用户信息
    	 Account account = getLoginAccount();
    	 Map<String,Object> result = new HashMap<String, Object>();
         if (account == null || StringUtils.isBlank(account.getAccount())) {
        	 result.put("result", "needLogin");
             return JsonUtil.objectToJson(result);
         }
         //	获取前台传递的选中优惠券id
         String couponId = request.getParameter("couponId");
         //	获取前台传递的子订单code
         String sonorderCode = request.getParameter("sonorderCode");
         
         AccountCoupon accountCoupon = new AccountCoupon();
         accountCoupon.setId(couponId);
         accountCoupon.setUserId(account.getId());
         AccountCoupon coupon = accountCouponService.selectAccountCouponInfo(accountCoupon);
         if (coupon.getStatus() == 2) {
        	 result.put("result", "couponUsed");
             return JsonUtil.objectToJson(result);
         }
         //从redis中获取父订单
         Order parentOrder = (Order) redisCacheProvider.get(account.getId() + "parentOrder");
         //取得父订单中子订单list
         List<Order> sonOrderList = parentOrder.getOrders();
         Order sonOrder = new Order();
         for (int i = 0; i < sonOrderList.size(); i++) {
             Order order = sonOrderList.get(i);
             logger.info("son orderCodeView is " + sonOrder.getOrderCodeView());
             if (order.getOrderCodeView().equals(sonorderCode)) {
            	 sonOrder = order;
                 break;
             }
         }
         double sonAmount = Double.valueOf(sonOrder.getAmount());
         double couponValue = Double.valueOf(coupon.getCouponValue());
         // 1 :抵价券    2：折扣券
         if(coupon.getCouponType()==2) {
        	 sonAmount = sonAmount * (couponValue/10);
         } else {
        	 sonAmount = sonAmount - couponValue;
        	 if(sonAmount<0) {
        		 sonAmount = 0;
        	 }
         }
         result.put("result", sonAmount);
    	 return JsonUtil.objectToJson(result);
    }
    
    protected CartInfo getMyCart()
    {
    	//return (CartInfo) RequestHolder.getSession().getAttribute(FrontContainer.myCart);
    	Account account = LoginUserHolder.getLoginAccount();    //得到登录用户的信息
    	CartInfo cartInfo = null;
    	if(account==null)
		{
			cartInfo = (CartInfo) redisCacheProvider.get("myCart");
		}
		else
		{
			cartInfo = (CartInfo) redisCacheProvider.get("user_"+account.getId()+"Cart");
		}
    	return cartInfo;
    }


}
